package mixedserver.protocol.jsonrpc;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.thx.common.util.ThreadLocalContext;
import com.thx.common.web.WebConstant;

@SuppressWarnings("serial")
public class ThxRPC extends RPC {
	public static final String AGENT_TYPE = "agent_type";
	public static final String AGENT_DEVICE_INFOR = "agent_device_infor";

	private String cookieName = "";
	private String cookieValue = "";

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		Cookie[] cookies = req.getCookies();
		String crossDomain =req.getHeader("Access-Control-Allow-Credentials");
		if(crossDomain!=null&&Boolean.parseBoolean(crossDomain)){
			res.addCookie(new Cookie("JSESSIONID",req.getSession().getId()));
		}
		if(cookies!=null){
			for(int i=0; i < cookies.length; i++) {
				cookieName = cookies[i].getName();
				cookieValue = cookies[i].getValue();
				if(cookieName.equals(AGENT_TYPE)){
					req.setAttribute(WebConstant.ACCESS_TYPE, cookieValue);
					//System.out.println(WebConstant.ACCESS_TYPE +":"+cookieValue);
				}else if(cookieName.equals(AGENT_DEVICE_INFOR)){
					req.setAttribute(WebConstant.DEVICE, cookieValue);
					//System.out.println(WebConstant.DEVICE +":"+cookieValue);
				}
			}
		}
		ThreadLocalContext.set(WebConstant.CURRENT_REQUEST, req);
		super.doPost(req, res);
		ThreadLocalContext.remove(WebConstant.CURRENT_REQUEST);
	}

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		super.doGet(req, res);
	}

}
